//
//  AppDelegate.m
//  Ten
//
//  Created by 韦显光 on 2018/7/31.
//  Copyright © 2018年 xg韦. All rights reserved.
//

#import "AppDelegate.h"
#import "GuideViewController.h"
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#import "AppDelegate+UMeng.h"
#import <MeiQiaSDK/MQManager.h>


#endif
@interface AppDelegate ()<JPUSHRegisterDelegate,UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [MQManager initWithAppkey:@"e38a2a273becaaffbb2a84b341b56d0d" completion:^(NSString *clientId, NSError *error) {
        if (!error) {
            NSLog(@"美洽 SDK：初始化成功");
        } else {
            NSLog(@"error:%@",error);
        }
    }];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self uMengApplication:application didFinishedLaunchWithOptions:launchOptions];
    // Override point for customization after application launch.
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"b2f776d67c492f855a620a1c"
                          channel:nil
                 apsForProduction:NO
            advertisingIdentifier:nil];
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            //            [FuncPublic SaveDefaultInfo:registrationID Key:@"CID"];
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
    NSString*lastVersionCode=[FuncPublic GetDefaultInfo:@"version"];
    //加载程序中的info.plist文件获得当前程序的版本号
    NSString *nowValueCode = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    //比较两个版本号是否相同
    if(![lastVersionCode isEqualToString:nowValueCode]){
        [FuncPublic SaveDefaultInfo:nowValueCode Key:@"version"];
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        GuideViewController*secondViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"GuideView"];
        self.window.rootViewController=secondViewController;
        [self.window makeKeyAndVisible];
        
    }else
    {
        if ([WXGStr([FuncPublic GetDefaultInfo:@"token"])empty]) {
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"login" bundle:nil];
            UIViewController*secondViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
            self.window.rootViewController=secondViewController;
            [self.window makeKeyAndVisible];
        }

    }
    
    
    return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [MQManager registerDeviceToken:deviceToken];
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
//应用内推送
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSString *body = content.body;    // 推送消息体
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
//应用外推送
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSString *body = content.body;    // 推送消息体
    completionHandler();  // 系统要求执行这个方法
}
#endif

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [MQManager closeMeiqiaService];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [MQManager openMeiqiaService];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

@end
